package com.hr.grpc;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.StreamObserver;
import seaway.AudioServiceGrpc;
import seaway.AudioServiceOuterClass;

import java.util.concurrent.TimeUnit;

public class HelloGrpClient {
    public static void main(String[] args) throws InterruptedException {
        ManagedChannel localhost = ManagedChannelBuilder.forAddress("localhost", 9000).usePlaintext().build();
        AudioServiceGrpc.AudioServiceStub audioServiceStub = AudioServiceGrpc.newStub(localhost);
        StreamObserver<AudioServiceOuterClass.AudioRequest> audioRequestStreamObserver = audioServiceStub.sendAudio(new StreamObserver<AudioServiceOuterClass.AudioResponse>() {
            @Override
            public void onNext(AudioServiceOuterClass.AudioResponse audioResponse) {
                System.out.println("客户端收到了服务端的消息:"+audioResponse.getResult());
            }

            @Override
            public void onError(Throwable throwable) {
                System.out.println(Thread.currentThread().getName() + " 客户端异常:" + throwable.getMessage());
            }

            @Override
            public void onCompleted() {
                System.out.println("相应全部结束");
            }
        });

        for (int i = 0; i < 20; i++) {
            TimeUnit.SECONDS.sleep(1);
            audioRequestStreamObserver.onNext(AudioServiceOuterClass.AudioRequest.newBuilder().setResult("我是客户端A" + i).build());
            audioRequestStreamObserver.onCompleted();
        }

        localhost.awaitTermination(12, TimeUnit.SECONDS);
        System.out.println("客户端关闭");
        localhost.shutdown();
    }
}
